package com.zgjkhis.modules.charges.rest;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zgjkhis.exception.ServiceException;
import com.zgjkhis.logging.aop.log.Log;
import com.zgjkhis.modules.charges.domain.Logistics;
import com.zgjkhis.modules.charges.domain.PrescriptionOrder;
import com.zgjkhis.modules.charges.dto.ExpressDto;
import com.zgjkhis.modules.charges.service.LogisticsService;
import com.zgjkhis.modules.charges.service.PrescriptionService;
import com.zgjkhis.modules.charges.service.dto.LogisticsCriteria;
import com.zgjkhis.modules.charges.service.dto.LogisticsRouteDto;
import com.zgjkhis.modules.security.security.LoginUserUtil;
import com.zgjkhis.modules.system.domain.OrderAddress;
import com.zgjkhis.modules.system.domain.Store;
import com.zgjkhis.modules.system.service.OrderAddressService;
import com.zgjkhis.modules.system.service.StoreService;
import com.zgjkhis.modules.util.CharUtil;
import com.zgjkhis.utils.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author yxl
 * @Description
 * @Date 2021/7/19 19:13
 **/
@Api(tags = "收费：物流")
@RestController
@RequestMapping("/api/logistics")
@Slf4j
public class LogisticsController {

    @Resource
    private OrderAddressService orderAddressService;
    @Resource
    private StoreService storeService;
    @Resource
    private LogisticsService service;
    @Resource
    private PrescriptionService prescriptionService;

    @Log("发货")
    @ApiOperation("发货")
    @PostMapping(value = "/addOrder")
    public ResponseEntity<Object> addOrder(@Validated @RequestBody LogisticsCriteria criteria) {
        String[] orderNOs = criteria.getOrderNo().split(",");
        PrescriptionOrder order = this.prescriptionService.getOne(Wrappers.<PrescriptionOrder>query().lambda().eq(PrescriptionOrder::getOrderNo, orderNOs[0]).eq(PrescriptionOrder::getPharmacyId, LoginUserUtil.getPharmId()));

        if (CharUtil.isEmpty(order)) {
            throw new ServiceException("查无此订单");
        }
        List<PrescriptionOrder> list = new ArrayList<>();
        List<String> apiOrderNos = new ArrayList<>();
        if (orderNOs.length > 1) {
            list = this.prescriptionService.list(Wrappers.<PrescriptionOrder>query().lambda().in(PrescriptionOrder::getOrderNo, orderNOs));
            List<String> stringList = list.stream().map(r -> r.getSourceId()).distinct().collect(Collectors.toList());
            if (stringList.size() > 1) {
                throw new ServiceException("不同平台的订单不能统一发货");
            }
            apiOrderNos = list.stream().map(r -> r.getApiOrderNo()).collect(Collectors.toList());
        } else {
            apiOrderNos.add(order.getApiOrderNo());
        }
        Logistics logistics = new Logistics();
        BeanUtil.copyProperties(criteria, logistics);
        logistics.setPharmacyId(LoginUserUtil.getPharmId());
        logistics.setOrderNo(order.getOrderNo());
        logistics.setOperateUserId(SecurityUtils.getUserId().toString());
        logistics.setOperateUser(LoginUserUtil.getNickName());
        logistics.setOperateTime(new Date());
        this.service.addOrder(order, logistics, orderNOs, apiOrderNos);
        if (orderNOs.length > 1) {
            prescriptionService.update(Wrappers.<PrescriptionOrder>update().lambda()
                    .set(PrescriptionOrder::getOrderCondition, 5).ne(PrescriptionOrder::getOrderCondition, 4)
                    .in(PrescriptionOrder::getId, list.stream().map(r -> r.getId()).collect(Collectors.toList()))
            );
//            for (PrescriptionOrder prescriptionOrder : list) {
//                if (!prescriptionOrder.getOrderCondition().equals("4")) {
//                    PrescriptionOrder temp = new PrescriptionOrder();
//                    temp.setOrderCondition(5);
//                    temp.setId(prescriptionOrder.getId());
//                    prescriptionService.updateById(temp);
//                }
//            }
        } else {
            if (!order.getOrderCondition().equals("4")) {
                PrescriptionOrder temp = new PrescriptionOrder();
                temp.setOrderCondition(5);
                temp.setId(order.getId());
                prescriptionService.updateById(temp);
            }
        }
        return ResponseEntity.ok(true);
    }


    @Log("批量发货")
    @ApiOperation("批量发货")
    @PostMapping(value = "/addOrderList")
    public ResponseEntity<Object> addOrderList(@Validated @RequestBody List<LogisticsCriteria> list) {
        String errorMsg = "";
        Store store = storeService.getById(LoginUserUtil.getPharmId());
        for (LogisticsCriteria criteria : list) {
            try {
                criteria.setOffline(0);
                criteria.setExpressChannel(0);
                criteria.setExpressName("顺丰");
                PrescriptionOrder order = this.prescriptionService.getOne(Wrappers.<PrescriptionOrder>query().lambda().eq(PrescriptionOrder::getOrderNo, criteria.getOrderNo()).eq(PrescriptionOrder::getPharmacyId, LoginUserUtil.getPharmId()));
                if (CharUtil.isEmpty(order)) {
//                    throw new ServiceException("查无此订单");
                    errorMsg = errorMsg + order.getOrderNo() + "查无此单;";
                }
                List<String> apiOrderNos = new ArrayList<>();
                apiOrderNos.add(order.getApiOrderNo());
                Logistics logistics = new Logistics();
                BeanUtil.copyProperties(criteria, logistics);

                logistics.setSrcAddress(store.getAddress());
                logistics.setSrcCity(store.getCity());
                logistics.setSrcDistrict(store.getArea());
                logistics.setSrcName(store.getStoreName());
                logistics.setSrcPhone(store.getPhone());
                logistics.setSrcProvince(store.getProvince());

                logistics.setPharmacyId(LoginUserUtil.getPharmId());
                logistics.setOrderNo(order.getOrderNo());
                logistics.setOperateUserId(SecurityUtils.getUserId().toString());
                logistics.setOperateUser(LoginUserUtil.getNickName());
                logistics.setOperateTime(new Date());
                this.service.addOrder(order, logistics, criteria.getOrderNo().split(","), apiOrderNos);
                if (!order.getOrderCondition().equals("4")) {
                    PrescriptionOrder temp = new PrescriptionOrder();
                    temp.setOrderCondition(5);
                    temp.setId(order.getId());
                    prescriptionService.updateById(temp);
                }
            } catch (Exception e) {
                log.error("{}发货错误：{}", criteria.getOrderNo(), e);
                errorMsg = errorMsg + criteria.getOrderNo() + ":" + e.getCause().getMessage() + ";";
            }
        }
        if (CharUtil.isEmpty(errorMsg)) {
            return ResponseEntity.ok(true);
        } else {
            throw new ServiceException(errorMsg);
        }
    }


    @Log("查询门店和收件人")
    @ApiOperation("查询门店和收件人")
    @GetMapping(value = "/queryDestInfo")
    public ResponseEntity<Object> queryDestInfo(String orderNo) {
        PrescriptionOrder order = this.prescriptionService.getOne(Wrappers.<PrescriptionOrder>query().lambda().eq(PrescriptionOrder::getOrderNo, orderNo).eq(PrescriptionOrder::getPharmacyId, LoginUserUtil.getPharmId()));
        if (CharUtil.isEmpty(orderNo)) {
            throw new ServiceException("订单号不能为空");
        }
        if (CharUtil.isEmpty(order)) {
            throw new ServiceException("查无此订单");
        }
        String pharmacyId = LoginUserUtil.getPharmId();
        Store store = storeService.getById(pharmacyId);

        QueryWrapper<OrderAddress> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no", order.getOrderNo());
        OrderAddress address = this.orderAddressService.getOne(wrapper);

        Map map = new HashMap();
        map.put("store", store);
        map.put("order", address);

        return new ResponseEntity(map, HttpStatus.OK);
    }

    @Log("查询物流订单")
    @ApiOperation("查询物流订单")
    @GetMapping(value = "/queryOrder")
    public ResponseEntity<Object> queryOrder(String orderNo) {
        if (CharUtil.isEmpty(orderNo)) {
            throw new ServiceException("orderNo不能为null");
        }
        PrescriptionOrder order = this.prescriptionService.getOne(Wrappers.<PrescriptionOrder>query().lambda().eq(PrescriptionOrder::getOrderNo, orderNo).eq(PrescriptionOrder::getPharmacyId, LoginUserUtil.getPharmId()));
        if (CharUtil.isEmpty(order)) {
            throw new ServiceException("查无此订单");
        }
        return new ResponseEntity(this.service.queryOrder(order.getOrderNo()), HttpStatus.OK);
    }

    @Log("查询物流")
    @ApiOperation("查询物流")
    @GetMapping(value = "/queryLogistics")
    public ResponseEntity<LogisticsRouteDto> queryLogistics(String orderNo) {
        if (CharUtil.isEmpty(orderNo)) {
            throw new ServiceException("orderNo不能为null");
        }
        PrescriptionOrder order = this.prescriptionService.getOne(Wrappers.<PrescriptionOrder>query().lambda().eq(PrescriptionOrder::getId, orderNo).eq(PrescriptionOrder::getPharmacyId, LoginUserUtil.getPharmId()));
        if (CharUtil.isEmpty(order)) {
            throw new ServiceException("查无此订单");
        }
        return new ResponseEntity(this.service.queryLogistics(order.getOrderNo()), HttpStatus.OK);
    }

    @Log("查询物流路由")
    @ApiOperation("查询物流路由")
    @GetMapping(value = "/queryLogisticsById")
    public ResponseEntity<Object> queryLogisticsById(String logisticsId) {
        if (CharUtil.isEmpty(logisticsId)) {
            throw new ServiceException("logisticsId不能为null");
        }
        return new ResponseEntity(this.service.queryLogisticsFromInterface(logisticsId), HttpStatus.OK);
    }

    @Log("顺丰物流取消接口")
    @ApiOperation("顺丰物流取消接口")
    @GetMapping(value = "/cancelThirdOrder")
    public ResponseEntity<Object> cancelThirdOrder(String logisticsId) {
        if (CharUtil.isEmpty(logisticsId)) {
            throw new ServiceException("logisticsId不能为null");
        }
        return new ResponseEntity(this.service.cancelThirdOrder(logisticsId), HttpStatus.OK);
    }

    @Log("修改发货时间")
    @ApiOperation("修改发货时间")
    @PostMapping(value = "/update")
//    @PreAuthorize("@el.check('drug:edit')")
    public ResponseEntity<Object> update(@Validated @RequestBody ExpressDto resources) {
        PrescriptionOrder order = new PrescriptionOrder();
        order.setId(resources.getId());
        order.setNextTime(resources.getNextTime());
        order.setNextRemark(resources.getNextRemark());
        order.setNextFlag(2);
        prescriptionService.updateById(order);
        return ResponseEntity.ok(true);
    }

    @Log("处理延迟发货")
    @ApiOperation("处理延迟发货")
    @PostMapping(value = "/updateFlag")
//    @PreAuthorize("@el.check('drug:edit')")
    public ResponseEntity<Object> updateFlag(String orderId, String flag) {
        if (CharUtil.isEmpty(orderId) || CharUtil.isEmpty(flag)) {
            throw new ServiceException("参数异常");
        }
        PrescriptionOrder order = new PrescriptionOrder();
        order.setId(Long.valueOf(orderId));
        order.setNextFlag(Integer.valueOf(flag));
        prescriptionService.updateById(order);
        return ResponseEntity.ok(true);
    }

}
